{% extends 'layout_index.html' %} {% load static %} {% block css %}
    <link rel="stylesheet" href="{% static 'css/userhub.css' %}"/>
{% endblock %} {% block title %}
    <title>管理员账号管理</title>
{% endblock %} {% block main_content %}

    <div class="admin-container">
        <!-- 顶部操作栏 -->
        <form method="get" action="{% url 'user_hub' %}">
            <div class="search-area mb-4">
                <div class="search-group">
                    <input
                            type="text"
                            class="form-control"
                            id="searchInput"
                            placeholder="请输入账号名称搜索..."
                            value="{{ search_key }}"
                            name="q"
                    />
                    <button class="btn btn-info" type="submit" id="searchBtn">
                        <i class="fa-solid fa-magnifying-glass"></i> 搜索
                    </button>
                </div>
                <a href="{% url 'add_admin' %}" class="btn btn-success">
                    <i class="fa-solid fa-plus"></i> 添加管理员
                </a>
            </div>
        </form>

        <table class="table table-hover">
            <thead>
            <tr>
                <th width="10%">序号</th>
                <th width="35%"><i class="fa-solid fa-user"></i> 管理员账号</th>
                <th width="35%"><i class="fa-solid fa-key"></i> 密码</th>
                <th width="20%"><i class="fa-solid fa-gear"></i> 操作</th>
            </tr>
            </thead>
            <tbody id="adminTableBody">
            {% for admin in admins %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <!-- 序号 -->
                    <td>{{ admin.username }}</td>
                    <!-- 管理员账号 -->
                    <td>{% if admin.username == 'admin' %}******{% else %}{{ admin.password }}{% endif %}</td>
                    <!-- 密码 -->
                    <td>
                        <div class="btn-group-action" style="display: flex; gap: 10px; align-items: center;">
                            {% if admin.username != 'admin' %}
                            <form
                                    method="post"
                                    action="{% url 'reset_password' admin.username %}"
                                    style="display: inline"
                            >
                                {% csrf_token %}
                                <button
                                        class="btn btn-md btn-info reset-btn"
                                        data-id="{{ admin.username }}"
                                >
                                    <i class="fa-solid fa-key"></i> 重置密码
                                </button>
                            </form>
                            <form
                                    method="post"
                                    action="{% url 'delete_admin' admin.username %}"
                                    style="display: inline"
                            >
                                {% csrf_token %}
                                <button class="btn btn-md btn-danger delete-btn"
                                        data-id="{{ admin.username }}">
                                    <i class="fa-solid fa-trash"></i> 删除
                                </button>
                            </form>
                            {% if admin.username != request.session.username %}
                                <button
                                        class="btn btn-md toggle-superuser-btn"
                                        style="margin-left: 0; {% if admin.is_superuser %}background: #6c757d; color: #fff; border: none;{% else %}background: #ffc107; color: #fff; border: none;{% endif %}"
                                        data-id="{{ admin.username }}"
                                        data-superuser="{{ admin.is_superuser }}"
                                >
                                    <i class="fa-solid fa-crown"></i> {% if admin.is_superuser %}取消超级管理员{% else %}授予超级管理员{% endif %}
                                </button>
                            {% endif %}
                            {% endif %}
                        </div>
                    </td>
                </tr>
            {% empty %}
                <tr>
                    <td colspan="4" class="text-center">暂无管理员账号</td>
                </tr>
            {% endfor %}
            </tbody>
        </table>

        <!-- 通过 Django Pagination 实现简单分页 -->
        <div class="pagination-container">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <!-- 首页 -->
                    <li class="page-item {% if not admins.has_previous %}disabled{% endif %}">
                        <a class="page-link" href="?page=1">首页</a>
                    </li>
                    <!-- 上一页 -->
                    <li class="page-item {% if not admins.has_previous %}disabled{% endif %}">
                        <a class="page-link" href="{% if admins.has_previous %}?page=
                            {{ admins.previous_page_number }}{% else %}javascript:;{% endif %}">
                            <i class="fa fa-angle-left"></i>
                        </a>
                    </li>

                    <!-- 页码 -->
                    {% for page in admins.paginator.page_range %}
                        {% if page == admins.number %}
                            <li class="page-item active">
                                <span class="page-link">{{ page }}</span>
                            </li>
                        {% elif page > admins.number|add:'-3' and page < admins.number|add:'3'%}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page }}">{{ page }}</a>
                            </li>
                        {% endif %}
                    {% endfor %}

                    <!-- 下一页 -->
                    <li class="page-item {% if not admins.has_next %}disabled{% endif %}">
                        <a class="page-link" href="{% if admins.has_next %}?page=
                            {{ admins.next_page_number }}{% else %}javascript:;{% endif %}">
                            <i class="fa fa-angle-right"></i>
                        </a>
                    </li>
                    <!-- 末页 -->
                    <li class="page-item {% if not admins.has_next %}disabled{% endif %}">
                        <a class="page-link" href="?page={{ admins.paginator.num_pages }}">末页</a>
                    </li>
                </ul>
            </nav>
            <!-- 分页信息 -->
            <div class="text-center">
        <span class="text-muted small">
            第 {{ admins.number }}/{{ admins.paginator.num_pages }} 页，共 {{admins.paginator.count }} 条记录
        </span>
            </div>
        </div>
    </div>

{% endblock %} {% block js %}

    <script>
        $(document).ready(function () {
            // CSRF Token设置
            function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== "") {
                    const cookies = document.cookie.split(";");
                    for (let i = 0; i < cookies.length; i++) {
                        const cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) === name + "=") {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

            const csrftoken = getCookie("csrftoken");

            // 搜索功能
            $("#searchBtn").click(function (e) {
                e.preventDefault();
                const searchTerm = $("#searchInput").val().trim();

                $.ajax({
                    url: window.location.pathname,
                    type: "POST",
                    data: {
                        action: "search",
                        search_term: searchTerm,
                        csrfmiddlewaretoken: csrftoken,
                    },
                    success: function (response) {
                        if (response.status === "success") {
                            updateTable(response.admins);
                        } else {
                            alert("搜索失败：" + response.message);
                        }
                    },
                    error: function () {
                        alert("搜索请求失败，请稍后重试");
                    },
                });
            });

            // 回车触发搜索
            $("#searchInput").keypress(function (e) {
                if (e.which == 13) {
                    e.preventDefault();
                    $("#searchBtn").click();
                }
            });

            // 重置密码
            $(document).on("click", ".reset-btn", function (e) {
                e.preventDefault();
                const adminId = $(this).data("id");
                if (
                    confirm(
                        "确定要重置该管理员的密码吗？新密码将为：" + adminId + "@123Jxust"
                    )
                ) {
                    $.ajax({
                        url: window.location.pathname,
                        type: "POST",
                        data: {
                            action: "reset_password",
                            id: adminId,
                            csrfmiddlewaretoken: csrftoken,
                        },
                        success: function (response) {
                            if (response.status === "success") {
                                alert("密码重置成功！新密码为：" + adminId + "@123Jxust");
                                location.reload();
                            } else {
                                alert("密码重置失败：" + response.message);
                            }
                        },
                        error: function () {
                            alert("重置密码请求失败，请稍后重试");
                        },
                    });
                }
            });

            // 删除管理员
            $(document).on("click", ".delete-btn", function (e) {
                e.preventDefault();
                const adminId = $(this).data("id");
                if (confirm("确定要删除该管理员吗？此操作不可恢复！")) {
                    $.ajax({
                        url: window.location.pathname,
                        type: "POST",
                        data: {
                            action: "delete",
                            id: adminId,
                            csrfmiddlewaretoken: csrftoken,
                        },
                        success: function (response) {
                            if (response.status === "success") {
                                alert("管理员删除成功！");
                                location.reload();
                            } else {
                                alert("删除失败：" + response.message);
                            }
                        },
                        error: function () {
                            alert("删除请求失败，请稍后重试");
                        },
                    });
                }
            });

            // 授予/取消超级管理员
            $(document).on("click", ".toggle-superuser-btn", function () {
                var btn = $(this);
                var adminId = btn.data("id");
                $.ajax({
                    url: "/index/userhub/toggle_superuser/" + adminId + "/",
                    type: "POST",
                    data: {
                        csrfmiddlewaretoken: csrftoken,
                    },
                    success: function (response) {
                        if (response.status === "success") {
                            if (response.is_superuser) {
                                btn.html("<i class='fa-solid fa-crown'></i> 取消超级管理员");
                                btn.css({
                                    background: "#6c757d",
                                    color: "#fff",
                                    border: "none"
                                });
                            } else {
                                btn.html("<i class='fa-solid fa-crown'></i> 授予超级管理员");
                                btn.css({
                                    background: "#ffc107",
                                    color: "#fff",
                                    border: "none"
                                });
                            }
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function () {
                        alert("操作失败，请稍后重试");
                    },
                });
            });

            // 更新表格内容
            function updateTable(admins) {
                const tbody = $("#adminTableBody");
                tbody.empty();

                if (admins.length === 0) {
                    tbody.append(
                        '<tr><td colspan="4" class="text-center">暂无管理员账号</td></tr>'
                    );
                    return;
                }

                admins.forEach((admin, index) => {
                    let superBtn = "";
                    let deleteBtn = "";
                    let resetBtn = "";
                    let passwordDisplay = admin.username === "admin" ? "******" : admin.password;
                    if (admin.username !== "admin") {
                        resetBtn = `<button class="btn btn-md btn-info reset-btn" data-id="${admin.username}"><i class='fa-solid fa-key'></i> 重置密码</button>`;
                        if (admin.username !== "{{ request.session.username }}") {
                            if (admin.is_superuser) {
                                superBtn = `<button class="btn btn-md toggle-superuser-btn" style="margin-left: 0; background: #6c757d; color: #fff; border: none;" data-id="${admin.username}" data-superuser="true"><i class='fa-solid fa-crown'></i> 取消超级管理员</button>`;
                            } else {
                                superBtn = `<button class="btn btn-md toggle-superuser-btn" style="margin-left: 0; background: #ffc107; color: #fff; border: none;" data-id="${admin.username}" data-superuser="false"><i class='fa-solid fa-crown'></i> 授予超级管理员</button>`;
                            }
                        }
                        deleteBtn = `<button class="btn btn-md btn-danger delete-btn" data-id="${admin.username}"><i class='fa-solid fa-trash'></i> 删除</button>`;
                    }
                    const row = `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${admin.username}</td>
                            <td>${passwordDisplay}</td>
                            <td>
                                <div class='btn-group-action' style='display: flex; gap: 10px; align-items: center;'>
                                    ${resetBtn}
                                    ${deleteBtn}
                                    ${superBtn}
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            }
        });
    </script>

{% endblock %}
